import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:smart_ai_dart/pages/learn_page/controller.dart';
import 'package:smart_ai_dart/utils/log_utils.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';

class VideoPlayerExample extends StatefulWidget {
  const VideoPlayerExample({super.key});

  @override
  _VideoPlayerExampleState createState() => _VideoPlayerExampleState();
}

class _VideoPlayerExampleState extends State<VideoPlayerExample> {
  late Player player;
  late VideoController controller;
  String videoUrl = 'https://www.runoob.com/try/demo_source/mov_bbb.mp4';

  @override
  void initState() {
    super.initState();
    player = Player(
      configuration: PlayerConfiguration(
        muted: false,
        title: 'HTML5 Video(视频)',
        ready: () {
          LogUtils.shared.i('The initialization is complete.');
        },
      ),
    );
    controller = VideoController(player);

    player.open(Media(videoUrl));
    // 监听播放状态变化
    player.stream.playing.listen((state) {
      LogUtils.shared.d(state);
    });
    // player.stream.position.listen((state) {
    //   LogUtils.shared.d(state);
    //   LogUtils.shared.d('===stream.position===');
    // });
    player.stream.completed.listen((state) {
      LogUtils.shared.d(state);
      LogUtils.shared.d('====stream.completed====');
    });
    player.stream.volume.listen((volume) {
      if (volume == 0.0) {
        LogUtils.shared.d('当前静音');
      } else {
        LogUtils.shared.d('音量: $volume');
      }
    });
    controller.player;
  }

  @override
  void dispose() {
    player.dispose();
    super.dispose();
    // 退出页面时恢复正常
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
  }

  Future<void> playVideo() async {
    // await player
    //     .open(Media(videoUrl));
    LogUtils.shared.d(player.state.volume);
    LogUtils.shared.d('=====================');
    if (player.state.playing) {
      player.pause();
    } else {
      player.play();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        AspectRatio(
          aspectRatio: 16 / 9,
          child: Video(
            controller: controller,
            controls: AdaptiveVideoControls,
            // controls: (state) {
            //   return Center(
            //     child: IconButton(
            //       onPressed: () {
            //         state.widget.controller.player.playOrPause();
            //       },
            //       icon: StreamBuilder(
            //         stream: state.widget.controller.player.stream.playing,
            //         builder: (context, playing) => Icon(
            //           playing.data == true ? Icons.pause : Icons.play_arrow,
            //         ),
            //       ),
            //     ),
            //   );
            // },
          ),
        ),
        ElevatedButton(
          onPressed: playVideo,
          child: const Text('Play Video'),
        ),
      ],
    );
  }
}

class LearnPage extends GetView<LearnController> {
  const LearnPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('learn'.tr),
      ),
      body: Column(
        children: [
          // const VideoPlayerExample(),
          Expanded(
            child: ListView(
              children: [
                const VideoPlayerExample(),
                _buildCategorySection(),
                _buildRecommendedCourses(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCategorySection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: Text(
            'learn_categories'.tr,
            style: Get.textTheme.titleLarge,
          ),
        ),
        SizedBox(
          height: 100,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: controller.categories.length,
            itemBuilder: (context, index) {
              final category = controller.categories[index];
              return _buildCategoryItem(category);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildCategoryItem(Map<String, dynamic> category) {
    return Container(
      width: 120,
      margin: const EdgeInsets.symmetric(horizontal: 8),
      decoration: BoxDecoration(
        color: Colors.blue.shade100,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(category['icon'], size: 40),
          const SizedBox(height: 8),
          Text(category['name']),
        ],
      ),
    );
  }

  Widget _buildRecommendedCourses() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: Text(
            'recommended_courses'.tr,
            style: Get.textTheme.titleLarge,
          ),
        ),
        ListView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: controller.recommendedCourses.length,
          itemBuilder: (context, index) {
            final course = controller.recommendedCourses[index];
            return _buildCourseItem(course);
          },
        ),
      ],
    );
  }

  Widget _buildCourseItem(Map<String, dynamic> course) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: ListTile(
        leading: SizedBox(
          width: 60,
          height: 60,
          child: Image.network(
            course['coverUrl'],
            fit: BoxFit.cover,
          ),
        ),
        title: Text(course['title']),
        subtitle: Text(course['description']),
        trailing: Text('${course['price']} ${course['currency']}'),
        onTap: () => controller.openCourseDetail(course['id']),
      ),
    );
  }
}
